/**
 * 
 */
package net.toocruel.iqismart.dao.spec;

import net.toocruel.iqismart.dao.condition.UserCondition;
import net.toocruel.iqismart.dao.support.BaseSpecification;
import net.toocruel.iqismart.dao.support.QueryWraper;
import net.toocruel.iqismart.entity.rbac.User;
import org.apache.commons.lang.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Root;

/**
 * @author toocruel
 *
 */
public class UserSpec extends BaseSpecification<User, UserCondition> {

	public UserSpec(UserCondition condition) {
		super(condition);
	}

	@Override
	protected void addCondition(QueryWraper<User> queryWraper) {
		CriteriaBuilder cb = queryWraper.getCb();
		Root<User> root = queryWraper.getRoot();

		if(StringUtils.isNotBlank(getCondition().getUsernameOrEmailOrMobile())){
			queryWraper.addPredicate(cb.or(
					cb.equal(root.get("username"), getCondition().getUsernameOrEmailOrMobile()),
					cb.equal(root.get("email"), getCondition().getUsernameOrEmailOrMobile()),
					cb.equal(root.get("mobile"), getCondition().getUsernameOrEmailOrMobile())
			));
		}

		if(getCondition().getStatus()!=null){
			queryWraper.addPredicate(cb.equal(root.get("status"),getCondition().getStatus()));
		}

		if(getCondition().getCreatedAtStart() != null && getCondition().getCreatedAtEnd() != null){
			queryWraper.addPredicate(cb.greaterThanOrEqualTo(root.get("createdAt"),getCondition().getCreatedAtStart()));
			queryWraper.addPredicate(cb.lessThanOrEqualTo(root.get("createdAt"),getCondition().getCreatedAtEnd()));
		}

		if(StringUtils.isNotBlank(getCondition().getUid())){
			queryWraper.addPredicate(cb.equal(root.get("id"),getCondition().getUid()));
		}
		if(StringUtils.isNotBlank(getCondition().getUsername())){
			queryWraper.addPredicate(cb.equal(root.get("username"),getCondition().getUsername()));
		}
		if(StringUtils.isNotBlank(getCondition().getMobile())){
			queryWraper.addPredicate(cb.equal(root.get("mobile"),getCondition().getMobile()));
		}
		if(StringUtils.isNotBlank(getCondition().getEmail())){
			queryWraper.addPredicate(cb.equal(root.get("email"),getCondition().getEmail()));
		}


	}

	@Override
	protected void addFetch(Root<User> root) {
		root.fetch("roles");
	}
}
